import http from './request.js';

class EditProfile {
    constructor() {
        this.init();
    }

    init() {
        // 确保 DOM 已加载
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initializeElements());
        } else {
            this.initializeElements();
        }
    }

    initializeElements() {
        this.photoInput = document.getElementById('photoInput');
        this.previewPhoto = document.getElementById('previewPhoto');
        this.nameInput = document.getElementById('name');
        this.bioInput = document.getElementById('bio');
        this.itemContainers = document.querySelectorAll('.item-container');
        this.saveBtn = document.querySelector('.save-btn');
        this.addBtns = document.querySelectorAll('.add-btn');
        this.changePasswordBtn = document.querySelector('.change-password-btn');
        this.passwordModal = document.getElementById('passwordModal');
        this.passwordForm = document.getElementById('passwordForm');

        this.loadUserInfo();
        this.bindEvents();
    }

    bindEvents() {
        // 头像上传
        if (this.photoInput) {
            this.photoInput.addEventListener('change', async (e) => {
                const file = e.target.files[0];
                if (file) {
                    await this.handlePhotoUpload(file);
                }
            });
        }

        // 添加项目按钮
        this.addBtns.forEach((btn, index) => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const types = ['Interest', 'Course', 'Achievement'];
                this.showAddItemDialog(types[index]);
            });
        });

        // 保存按钮
        if (this.saveBtn) {
            this.saveBtn.addEventListener('click', async (e) => {
                e.preventDefault();
                await this.handleSave();
            });
        }

        // 修改密码按钮点击事件
        if (this.changePasswordBtn) {
            this.changePasswordBtn.addEventListener('click', () => {
                this.passwordModal.style.display = 'block';
            });
        }

        // 关闭模态框
        const closeBtn = this.passwordModal.querySelector('.close');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => {
                this.passwordModal.style.display = 'none';
            });
        }

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target === this.passwordModal) {
                this.passwordModal.style.display = 'none';
            }
        });

        // 密码表单提交
        if (this.passwordForm) {
            this.passwordForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                await this.handlePasswordChange();
            });
        }
    }

    // 加载用户信息
    async loadUserInfo() {
        try {
            const studentId = http.getUserInfo().id;
            if (studentId) {
                const student = await http.get(`/students/${studentId}`);
                this.fillFormData(student);
            }
        } catch (error) {
            console.error('Failed to load user info:', error);
        }
    }


    // 填充表单数据
    fillFormData(student) {
        this.nameInput.value = student.Name || '';
        this.bioInput.value = student.Bio || '';
        
        if (student.Photo) {
            this.previewPhoto.src = student.Photo;
            this.photoPath = student.Photo;
        }

        // 填充兴趣列表
        const interests = student.Interests ? student.Interests.split(',') : [];
        this.renderItems(interests, 0);

        // 填充课程列表
        const courses = student.Courses ? student.Courses.split(',') : [];
        this.renderItems(courses, 1);

        // 填充成就列表
        const achievements = student.Achievements ? student.Achievements.split(',') : [];
        this.renderItems(achievements, 2);
    }

    // 渲染列表项
    renderItems(items, containerIndex) {
        const container = this.itemContainers[containerIndex];
        container.innerHTML = items.map(item => `
            <div class="item">
                <button type="button" class="remove-btn" onclick="this.parentElement.remove()">&times;</button>
                <span>${item}</span>
            </div>
        `).join('');
    }

    // 显示添加项目对话框
    showAddItemDialog(type) {
        const value = prompt(`Add new ${type}:`);
        if (value && value.trim()) {
            const index = ['Interest', 'Course', 'Achievement'].indexOf(type);
            if (index !== -1 && this.itemContainers[index]) {
                const container = this.itemContainers[index];
                const itemDiv = document.createElement('div');
                itemDiv.className = 'item';
                itemDiv.innerHTML = `
                    <span>${value.trim()}</span>
                    <button type="button" class="remove-btn">&times;</button>
                `;
                
                // 绑定删除按钮事件
                const removeBtn = itemDiv.querySelector('.remove-btn');
                removeBtn.addEventListener('click', () => itemDiv.remove());
                
                container.appendChild(itemDiv);
            }
        }
    }

    // 处理头像上传
    async handlePhotoUpload(file) {
        try {

            const formData = new FormData();
            formData.append('file', file);
            
            const result = await http.post('/upload', formData);
            this.previewPhoto.src = result.url;
            this.photoPath = result.url;
        } catch (error) {
            console.error('Upload failed:', error);
        }
    }

    // 获取列表项的值
    getItemValues(containerIndex) {
        const container = this.itemContainers[containerIndex];
        return Array.from(container.querySelectorAll('.item span'))
            .map(span => span.textContent.trim());
    }

    // 处理保存
    async handleSave() {
        try {
            const studentId = http.getUserInfo().id;
            const formData = {
                studentId,
                name: this.nameInput.value,
                bio: this.bioInput.value,
                photo: this.photoPath,
                interests: this.getItemValues(0).join(','),
                courses: this.getItemValues(1).join(','),
                achievements: this.getItemValues(2).join(',')
            };

            await http.put(`/students/${studentId}`, formData);
            let student = await http.get(`/students/${studentId}`);
            http.setUserInfo({id: student.StudentID, name: student.Name, bio: student.Bio, photo: student.Photo})
            alert('Profile updated successfully!');
            window.location.href = '/edit-profile.html';
        } catch (error) {
            console.error('Save failed:', error);
            alert('Failed to update profile: ' + error.message);
        }
    }

    // 添加处理密码修改的方法
    async handlePasswordChange() {
        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        // 验证新密码
        if (newPassword !== confirmPassword) {
            alert('New passwords do not match!');
            return;
        }

        if (newPassword.length < 6) {
            alert('New password must be at least 6 characters long!');
            return;
        }

        try {
            const userInfo = http.getUserInfo();
            const response = await http.post('/reset-password', {
                email: userInfo.email,
                password: currentPassword,
                newPassword: newPassword
            });

            alert('Password changed successfully!');
            this.passwordModal.style.display = 'none';
            this.passwordForm.reset();
        } catch (error) {
            console.error('Password change failed:', error);
            alert(error.message || 'Failed to change password');
        }
    }
}

// 初始化编辑个人信息面
new EditProfile(); 